<template>
	<view class="container">
		<!-- 头部 -->
		<view class="header">
			<view class="header-content">
				<text class="title">父母情绪日志</text>
				<text class="subtitle">来看看今天父母的心情吧!</text>
			</view>
		</view>

		<!-- 父母选择标签 -->
		<view class="parent-tabs">
			<view 
				class="tab-item" 
				:class="{ active: selectedParent === 'father' }"
				@tap="selectParent('father')"
			>
				<text class="tab-text">父亲</text>
			</view>
			<view 
				class="tab-item" 
				:class="{ active: selectedParent === 'mother' }"
				@tap="selectParent('mother')"
			>
				<text class="tab-text">母亲</text>
			</view>
		</view>

		<!-- 今日情绪 -->
		<view class="today-mood">
			<text class="section-title">今日情绪</text>
			<view class="mood-card">
				<view class="mood-icon">{{currentMood.emoji}}</view>
				<view class="mood-info">
					<text class="mood-level">{{currentMood.level}}</text>
					<text class="mood-desc">{{currentMood.description}}</text>
					<text class="mood-time">{{currentMood.time}}</text>
				</view>
			</view>
		</view>

		<!-- 情绪趋势 -->
		<view class="mood-trend">
			<text class="section-title">最近7天情绪趋势</text>
			<view style="background: #ffffff; border-radius: 16rpx; padding: 30rpx; box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);">
				<canvas canvas-id="trendCanvas" class="trend-canvas"></canvas>
			</view>
		</view>

		<!-- 情绪记录列表 -->
		<view class="mood-history">
			<text class="section-title">情绪记录</text>
			<view class="history-list">
				<view class="history-item" v-for="(item, index) in moodHistory" :key="index" @tap="openAnalysis(item)">
					<view class="history-icon">{{item.emoji}}</view>
					<view class="history-content">
						<text class="history-level">{{item.emotion}}</text>
						<text class="history-desc">{{item.description}}</text>
						<text class="history-time">{{item.time}}</text>
					</view>
					<view class="history-status" :class="item.status">
						<text class="status-text">{{item.statusText}}</text>
					</view>
				</view>
			</view>

			<view style="padding: 24rpx; text-align:center;">
				<view @tap="goMore" style="display:inline-block; padding: 16rpx 24rpx; background:#f0f2f5; border-radius: 12rpx; color:#3d5a80;">更多日期...</view>
			</view>
		</view>

		<!-- 详细对话分析 -->
		<view class="conversation-analysis">
			<text class="section-title">今日对话分析</text>
			<view class="conversation-list">
				<view class="conversation-item" v-for="(conv, index) in todayConversations" :key="index">
					<view class="conversation-header">
						<text class="conversation-time">{{conv.time}}</text>
						<view class="conversation-emotion">
							<text class="emotion-emoji">{{conv.emoji}}</text>
							<text class="emotion-text">{{conv.emotion}}</text>
						</view>
					</view>
					<text class="conversation-content">{{conv.content}}</text>
					<text class="conversation-analysis-text">{{conv.description}}</text>
				</view>
			</view>
		</view>

		<!-- 加载状态 -->
		<view class="loading" v-if="loading">
			<text class="loading-text">正在分析情绪数据...</text>
		</view>
	</view>
</template>

<script>
	// 尝试使用相对路径导入
import apiService from '../../utils/api.js';
	
	export default {
		data() {
			return {
				selectedParent: 'father',
				loading: false,
				currentMood: {
					emoji: '😊',
					level: '良好',
					description: '今天心情不错，和邻居聊得很开心',
					time: '今天 14:30'
				},
                sevenSeries: [], // 近7天曲线数据
				moodTrend: [
					{ day: '周一', height: 60 },
					{ day: '周二', height: 80 },
					{ day: '周三', height: 40 },
					{ day: '周四', height: 70 },
					{ day: '周五', height: 90 },
					{ day: '周六', height: 85 },
					{ day: '周日', height: 75 }
				],
				moodHistory: [],
				todayConversations: []
			}
		},
		onLoad() {
			const sys = uni.getSystemInfoSync();
			this.screenWidth = sys.windowWidth || 375;
			this.loadMoodData();
		},
		methods: {
			async selectParent(parent) {
				this.selectedParent = parent;
				await this.loadMoodData();
			},
			
			// 格式化日期
	formatDate(date) {
		const d = new Date(date);
		const month = (d.getMonth() + 1).toString().padStart(2, '0');
		const day = d.getDate().toString().padStart(2, '0');
		return `${month}月${day}日`;
	},
	
	// 生成模拟数据
	getMockData() {
		const mockCurrentMood = {
			emoji: '😊',
			level: '良好',
			description: '今天心情不错，整体情绪平静',
			time: '今天 ' + new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
		};
		
		const mockTodayConversations = [
			{
				time: '09:30',
				content: '今天天气真好，记得多出去走走',
				emoji: '😊',
				emotion: '开心',
				description: '积极愉悦'
			},
			{
				time: '12:15',
				content: '中午吃的什么？不要太油腻了',
				emoji: '😟',
				emotion: '关心',
				description: '关心家人'
			},
			{
				time: '18:45',
				content: '晚上早点休息，别熬夜了',
				emoji: '😴',
				emotion: '疲惫',
				description: '身心疲惫'
			}
		];
		
		const mockMoodHistory = [];
		const today = new Date();
		for (let i = 1; i <= 7; i++) {
			const d = new Date(today);
			d.setDate(d.getDate() - i);
			const dateStr = d.toISOString().split('T')[0];
			const month = (d.getMonth() + 1).toString().padStart(2, '0');
			const day = d.getDate().toString().padStart(2, '0');
			mockMoodHistory.push({
				date: dateStr,
				emoji: ['😊', '😐', '😔'][Math.floor(Math.random() * 3)],
				emotion: ['开心', '平静', '低落'][Math.floor(Math.random() * 3)],
				description: `整体情绪${['开心', '平静', '低落'][Math.floor(Math.random() * 3)]}`,
				time: `${month}月${day}日`,
				status: ['good', 'normal', 'low'][Math.floor(Math.random() * 3)],
				statusText: ['正常', '正常', '关注'][Math.floor(Math.random() * 3)]
			});
		}
		
		const mockSevenSeries = mockMoodHistory.slice(0, 7).reverse().map((item, index) => ({
			date: item.date,
			score: 40 + Math.floor(Math.random() * 55),
			emoji: item.emoji,
			emotion: item.emotion,
			level: ['良好', '一般', '需要关注'][Math.floor(Math.random() * 3)]
		}));
		
		return {
			currentMood: mockCurrentMood,
			todayConversations: mockTodayConversations,
			moodHistory: mockMoodHistory,
			sevenSeries: mockSevenSeries
		};
	},
	
	async loadMoodData() {
			this.loading = true;
			try {
				// 检查apiService是否可用
				if (!apiService) {
					console.warn('apiService不可用，使用模拟数据');
					const mockData = this.getMockData();
					this.currentMood = mockData.currentMood;
					this.todayConversations = mockData.todayConversations;
					this.moodHistory = mockData.moodHistory;
					this.sevenSeries = mockData.sevenSeries;
					this.$nextTick(() => this.drawTrend());
					this.loading = false;
					return;
				}
				
				// 获取今日情绪（优先使用后端API）
				const todayMood = await apiService.getTodayMood(this.selectedParent);
				
				// 有聊天记录时正常显示
				this.currentMood = {
					emoji: todayMood.emoji,
					level: todayMood.level,
					description: `整体情绪${todayMood.emotion}，${todayMood.level}`,
					time: '今天 ' + new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
				};

				// 获取今日对话
				const today = new Date().toISOString().split('T')[0];
				const conversations = await apiService.getParentConversations(this.selectedParent, today);
				const analysis = await apiService.analyzeEmotion(conversations.conversations);
				this.todayConversations = analysis.conversations.map(conv => ({
					time: conv.time,
					content: conv.content,
					emoji: conv.emoji,
					emotion: conv.emotion,
					description: conv.description
				}));

				// 获取情绪历史（按日期降序展示）
				const history = await apiService.getLastNDaysHistory(this.selectedParent, 7);
				history.sort((a, b) => new Date(b.date) - new Date(a.date));
				this.moodHistory = history.map(item => ({
					date: item.date,
					emoji: item.mood?.emoji || '😐',
					emotion: item.mood?.emotion || '平静',
					description: `整体情绪${item.mood?.emotion || '平静'}`,
					time: this.formatDate(item.date),
					status: item.mood?.level === '良好' ? 'good' : item.mood?.level === '一般' ? 'normal' : 'low',
					statusText: item.mood?.level === '良好' ? '正常' : item.mood?.level === '一般' ? '正常' : '关注'
				}));

				// 近7天曲线数据并绘制 - 使用更新后的API
				this.sevenSeries = await apiService.getSevenDaySeries(this.selectedParent);
				this.$nextTick(() => this.drawTrend());

			} catch (error) {
				console.error('加载情绪数据失败:', error);
				// 出错时使用模拟数据
				const mockData = this.getMockData();
				this.currentMood = mockData.currentMood;
				this.todayConversations = mockData.todayConversations;
				this.moodHistory = mockData.moodHistory;
				this.sevenSeries = mockData.sevenSeries;
				this.$nextTick(() => this.drawTrend());
			} finally {
				this.loading = false;
			}
		},
        

		// 画曲线
		drawTrend() {
			// 确保有数据
			if (!this.sevenSeries || this.sevenSeries.length === 0) {
				console.warn('没有情绪数据可绘制');
				// 使用模拟数据
				this.sevenSeries = this.generateMockSevenSeries();
			}

			const toPx = (rpx) => rpx * (this.screenWidth || 375) / 750;
			const series = this.sevenSeries;
			const cw = toPx(690); // 与样式 690rpx 对齐
			const ch = toPx(260); // 与样式 260rpx 对齐
			const left = 40, right = 20, top = 30, bottom = 40;
			const w = cw - left - right;
			const h = ch - top - bottom;

			const ctx = uni.createCanvasContext('trendCanvas', this);
			// 清空画布
			ctx.setFillStyle('#ffffff');
			ctx.fillRect(0, 0, cw, ch);

			// 坐标与网格线
			ctx.setStrokeStyle('#f0f0f0');
			ctx.setLineWidth(1);
			// 水平线
			for (let i = 0; i <= 4; i++) {
				const y = top + (h / 4) * i;
				ctx.moveTo(left, y);
				ctx.lineTo(left + w, y);
			}
			ctx.stroke();

			// 计算数据点坐标
			const xs = series.map((_, i) => left + (w / (series.length - 1)) * i);
			const ys = series.map(s => {
				// 确保分数在合理范围内
				const score = s.score || 50;
				const minScore = 30;
				const maxScore = 95;
				const ratio = (score - minScore) / (maxScore - minScore);
				return top + (1 - Math.max(0, Math.min(1, ratio))) * h;
			});

			// 绘制曲线（使用平滑曲线连接点）
			ctx.beginPath();
			ctx.setStrokeStyle('#667eea');
			ctx.setLineWidth(3);
			ctx.setLineCap('round');
			ctx.setLineJoin('round');
			
			// 绘制平滑曲线
			if (xs.length > 1) {
				// 移动到第一个点
				ctx.moveTo(xs[0], ys[0]);
				
				// 使用二次贝塞尔曲线绘制平滑曲线
				for (let i = 1; i < xs.length - 1; i++) {
					const xc = (xs[i] + xs[i + 1]) / 2;
					const yc = (ys[i] + ys[i + 1]) / 2;
					ctx.quadraticCurveTo(xs[i], ys[i], xc, yc);
				}
				
				// 绘制最后一段
				ctx.lineTo(xs[xs.length - 1], ys[ys.length - 1]);
			}
			ctx.stroke();

			// 绘制数据点
			xs.forEach((x, i) => {
				const y = ys[i];
				// 外圈
				ctx.beginPath();
				ctx.setStrokeStyle('#667eea');
				ctx.setLineWidth(2);
				ctx.setFillStyle('#ffffff');
				ctx.arc(x, y, 6, 0, Math.PI * 2);
				ctx.fill();
				ctx.stroke();
				// 内圈
				ctx.beginPath();
				ctx.setFillStyle('#667eea');
				ctx.arc(x, y, 3, 0, Math.PI * 2);
				ctx.fill();
			});

			// 绘制标签：emoji + 日期
			ctx.setFontSize(14);
			ctx.setTextAlign('center');
			series.forEach((s, i) => {
				const x = xs[i], y = ys[i];
				// 情绪emoji
				ctx.setFillStyle('#333333');
				ctx.fillText(s.emoji || '😐', x, y - 12);
				// 日期
				const d = new Date(s.date);
				const label = `${d.getMonth() + 1}/${d.getDate()}`;
				ctx.setFontSize(12);
				ctx.setFillStyle('#666666');
				ctx.fillText(label, x, top + h + 18);
			});

			// 执行绘制
			ctx.draw();
		},
		
		// 生成模拟的7天数据，确保图表有内容显示
		generateMockSevenSeries() {
			const series = [];
			const today = new Date();
			const emotions = ['😊', '😐', '😔', '😃', '😕'];
			const emotionLabels = ['开心', '平静', '低落', '兴奋', '担忧'];
			const levels = ['良好', '一般', '需要关注', '良好', '一般'];
			
			for (let i = 6; i >= 0; i--) {
				const date = new Date(today);
				date.setDate(date.getDate() - i);
				const randomIndex = Math.floor(Math.random() * emotions.length);
				series.push({
					date: date.toISOString().split('T')[0],
					score: 40 + Math.floor(Math.random() * 50), // 40-90的随机分数
					emoji: emotions[randomIndex],
					emotion: emotionLabels[randomIndex],
					level: levels[randomIndex]
				});
			}
			return series;
		},

        

            updateTrendChart(history) {
				const trendData = history.map(item => {
					const score = item.mood.level === '良好' ? 80 : item.mood.level === '一般' ? 60 : 40;
					return { day: this.getDayName(item.date), height: score };
				});
				this.moodTrend = trendData;
			},

            openAnalysis(item) {
                const date = item.date || new Date().toISOString().split('T')[0];
                uni.navigateTo({ url: `/pages/chat-analysis/chat-analysis?parent=${this.selectedParent}&date=${date}` });
            },

            goMore() {
                uni.navigateTo({ url: `/pages/mood-log/more-dates?parent=${this.selectedParent}` });
            },

			formatDate(dateStr) {
				const date = new Date(dateStr);
				const today = new Date();
				const yesterday = new Date(today);
				yesterday.setDate(yesterday.getDate() - 1);

				if (dateStr === today.toISOString().split('T')[0]) {
					return '今天';
				} else if (dateStr === yesterday.toISOString().split('T')[0]) {
					return '昨天';
				} else {
					return `${date.getMonth() + 1}月${date.getDate()}日`;
				}
			},

			getDayName(dateStr) {
				const date = new Date(dateStr);
				const days = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				return days[date.getDay()];
			}
		}
	}
</script>

<style>
	.container {
		min-height: 100vh;
		background: linear-gradient(135deg, #f9f7f7 0%, #eaf4f4 100%);
		animation: pageLoad 0.6s ease-out;
	}

	@keyframes pageLoad {
		0% {
			opacity: 0;
			transform: translateY(20rpx);
		}
		100% {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.header {
		background: linear-gradient(135deg, #f8b195, #f67280);
		padding: 60rpx 30rpx 40rpx;
	}

	.header-content {
		text-align: center;
	}

	.title {
		display: block;
		font-size: 48rpx;
		font-weight: bold;
		color: #ffffff;
		margin-bottom: 10rpx;
	}

	.subtitle {
		font-size: 28rpx;
		color: rgba(255, 255, 255, 0.8);
	}

	/* 父母选择标签 */
	.parent-tabs {
		display: flex;
		background: #ffffff;
		margin: 20rpx 30rpx;
		border-radius: 12rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
		opacity: 0;
		animation: fadeIn 0.5s ease-out 0.3s forwards;
	}

	@keyframes fadeIn {
		0% {
			opacity: 0;
			transform: translateY(10rpx);
		}
		100% {
			opacity: 1;
			transform: translateY(0);
		}
	}

	.tab-item {
		flex: 1;
		padding: 30rpx;
		text-align: center;
		background: #ffffff;
		transition: all 0.3s ease;
	}

	.tab-item.active {
		background: linear-gradient(135deg, #f8b195, #f67280);
	}

	.tab-text {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
	}

	.tab-item.active .tab-text {
		color: #ffffff;
	}

	/* 今日情绪 */
	.today-mood {
		margin: 30rpx;
		opacity: 0;
		animation: fadeIn 0.5s ease-out 0.4s forwards;
	}

	.section-title {
		display: block;
		font-size: 32rpx;
		font-weight: bold;
		color: #3d5a80;
		margin-bottom: 20rpx;
		position: relative;
		padding-left: 16rpx;
	}

	.section-title::before {
		content: '';
		position: absolute;
		left: 0;
		top: 50%;
		transform: translateY(-50%);
		width: 8rpx;
		height: 32rpx;
		background: linear-gradient(180deg, #f8b195, #f67280);
		border-radius: 4rpx;
	}

	.mood-card {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		display: flex;
		align-items: center;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.08);
		transition: all 0.3s ease;
	}

	.mood-card:hover {
		transform: translateY(-2rpx);
		box-shadow: 0 6rpx 20rpx rgba(0, 0, 0, 0.1);
	}

	.mood-icon {
		font-size: 80rpx;
		margin-right: 30rpx;
	}

	.mood-info {
		flex: 1;
	}

	.mood-level {
		display: block;
		font-size: 36rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
	}

	.mood-desc {
		display: block;
		font-size: 26rpx;
		color: #666;
		margin-bottom: 8rpx;
	}

	.mood-time {
		font-size: 24rpx;
		color: #999;
	}

	/* 情绪趋势 */
	.mood-trend {
		margin: 30rpx;
		opacity: 0;
		animation: fadeIn 0.5s ease-out 0.5s forwards;
	}

	.trend-chart {
		background: #ffffff;
		border-radius: 16rpx;
		padding: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: end;
		height: 200rpx;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	}

	.chart-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		flex: 1;
	}

	.chart-bar {
		width: 20rpx;
		background: linear-gradient(180deg, #667eea, #764ba2);
		border-radius: 10rpx 10rpx 0 0;
		margin-bottom: 10rpx;
	}

/* canvas 尺寸 */
.trend-canvas {
	width: 690rpx;
	height: 260rpx;
	display: block;
	margin: 0 auto;
}

	/* 情绪记录列表 */
	.mood-history {
		margin: 30rpx;
		opacity: 0;
		animation: fadeIn 0.5s ease-out 0.6s forwards;
	}

	.history-list {
		background: #ffffff;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	}

	.history-item {
		display: flex;
		align-items: center;
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		transition: all 0.2s ease;
	}

	.history-item:hover {
		background: #f8f9fa;
	}

	.history-item:last-child {
		border-bottom: none;
	}

	.history-icon {
		font-size: 60rpx;
		margin-right: 20rpx;
	}

	.history-content {
		flex: 1;
	}

	.history-level {
		display: block;
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		margin-bottom: 8rpx;
	}

	.history-desc {
		display: block;
		font-size: 26rpx;
		color: #666;
		margin-bottom: 8rpx;
	}

	.history-time {
		font-size: 24rpx;
		color: #999;
	}

	.history-status {
		padding: 8rpx 16rpx;
		border-radius: 20rpx;
	}

	.history-status.good {
		background: #e8f5e8;
	}

	.history-status.normal {
		background: #fff3e0;
	}

	.history-status.low {
		background: #ffebee;
	}

	.status-text {
		font-size: 24rpx;
		color: #333;
	}

	/* 对话分析 */
	.conversation-analysis {
		margin: 30rpx;
		opacity: 0;
		animation: fadeIn 0.5s ease-out 0.7s forwards;
	}

	.conversation-list {
		background: #ffffff;
		border-radius: 16rpx;
		overflow: hidden;
		box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.1);
	}

	.conversation-item {
		padding: 30rpx;
		border-bottom: 1rpx solid #f0f0f0;
		transition: all 0.2s ease;
	}

	.conversation-item:hover {
		background: #f8f9fa;
	}

	.conversation-item:last-child {
		border-bottom: none;
	}

	.conversation-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 15rpx;
	}

	.conversation-time {
		font-size: 24rpx;
		color: #999;
	}

	.conversation-emotion {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}

	.emotion-emoji {
		font-size: 24rpx;
	}

	.emotion-text {
		font-size: 24rpx;
		color: #f67280;
		font-weight: bold;
	}

	.conversation-content {
		display: block;
		font-size: 28rpx;
		color: #333;
		line-height: 1.5;
		margin-bottom: 15rpx;
	}

	.conversation-analysis-text {
		font-size: 24rpx;
		color: #666;
		background: #f8f9fa;
		padding: 15rpx;
		border-radius: 8rpx;
		line-height: 1.4;
	}

	/* 加载状态 */
	.loading {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 1000;
	}

	.loading-text {
		color: #ffffff;
		font-size: 28rpx;
		background: rgba(0, 0, 0, 0.7);
		padding: 30rpx 40rpx;
		border-radius: 16rpx;
	}
</style>
